﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Web.Script.Serialization;
using Core.DataAccess;
using SonCa.SocialNetwork.Web.Accounts.IPresenters;
using SonCa.SocialNetwork.Web.Accounts.Presenters;
using System.Text;
using System.Security.Policy;

namespace SonCa.SocialNetwork.Web.Accounts
{
    public partial class Facebook : System.Web.UI.Page, IFacebook
    {
        private FacebookPresenter _presenter;

        protected void Page_Load(object sender, EventArgs e)
        {
            _presenter = new FacebookPresenter();
            _presenter.Init(this);

            LoginWithFacebookAccount();
        }

        private void LoginWithFacebookAccount()
        {
            string url = Request.Url.AbsoluteUri;
            if (url.Contains("access_token"))
            {
                try
                {
                    string accessToken = Request.QueryString["access_token"];
                    string requestUrl = "http://graph.facebook.com/me?access_token=" + accessToken;
                    WebClient client = new WebClient();// { Proxy = System.Net.WebProxy.GetDefaultProxy() };
                    client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
                    //client.Encoding = Encoding.UTF8;
                    string userInformation = client.DownloadString(requestUrl);

                    JavaScriptSerializer jss = new JavaScriptSerializer();
                    var user = jss.Deserialize<FacebookAccount>(userInformation);


                    if (user != null)
                    {
                        _presenter.LoginWithFacebookAccount(user);
                    }
                }
                catch (Exception ex)
                {
                    Label1.Visible = true;
                    Label1.Text = ex.Message;
                }
            }
        }
    }
}